<template>
    <div>
        <nut-overlay v-model:visible="disableUse" :close-on-click-overlay="false"></nut-overlay>
        <nut-cell :title="currentProduct ? currentProduct.name : '请选择产品'"
            :sub-title="currentProduct ? currentProduct.showrule : ''" @click="loadAndShowProducts">
        </nut-cell>
        <div class="scanArea">
            <view class="nut-tag nut-tag--warning tag-area" v-if="!currentProduct" type="warning"> 请选择产品 </view>
            <view class="nut-tag nut-tag--warning tag-area" v-if="currentProduct && !checkResult" type="warning"> 请扫描
            </view>
            <view class="nut-tag nut-tag--success tag-area" style="font-size: 12px;"
                v-if="checkResult && checkResult.pass" type="success">
                {{ scanedCode }} 通过
            </view>
            <div style="height:150px" class="nut-tag nut-tag--danger" v-if="checkResult && !checkResult.pass">
                <div style="font-size: 12px;display: block; background-color: white; padding:20px">
                    <div>
                        <span style="color: green;">{{ checkResult.passedContent }}</span>
                        <span style="color: red;">{{ checkResult.errorContent }}</span>
                        <span style="color: blue;">{{ checkResult.leftContent }}</span>
                    </div>
                    <div style="display: block;font-size: 12px; margin-top: 10px; color: red;">{{
                        checkResult.errorMessage }}</div>
                </div>
            </div>
        </div>
        <nut-popup v-model:visible="showProducts" position="right" :style="{ width: '80%', height: '100vh' }">
            <nut-list :list-data="products" :container-height="470" @scroll-bottom="onScrollBottom">
                <template #default="{ item }">
                    <nut-cell :title="item.name" :sub-title="item.showrule" @click="selCurrentP(item)">
                    </nut-cell>
                </template>
            </nut-list>
        </nut-popup>
        <view class="bottom-area">
            <view style="display:flex;width:80%;justify-content: space-between;">
                <nut-button type="info" @click="updateHistory">更新历史库</nut-button>
                <nut-button type="info" @click="updateProducts">更新规则库</nut-button>
            </view>
        </view>
        <nut-dialog teleport="#app" :title="reloadProgressName" :visible="reloadProgressName != ''" :no-footer="true">
            <nut-progress :percentage="reloadProgress" stroke-color="skyblue" stroke-width="15" text-color="green" />
        </nut-dialog>
        <nut-audio url="alert.wav" type="none" v-if="showAlert" autoplay=""></nut-audio>
    </div>
</template>
<script setup lang="js">
import * as ruleService from '@/api/rules';
import * as sqlService from '@/api/sqlutil';
import { showDialog } from '@nutui/nutui';
import {
onUnmounted, ref
} from 'vue';
const currentProduct = ref(null);
const showProducts = ref(false);
const products = ref([]);
const reloadProgressName = ref('');
const reloadProgress = ref(0);
const showAlert = ref(false);
const disableUse = ref(false);
const selCurrentP = (p) => {
    currentProduct.value = p;
    showProducts.value = false;
    checkResult.value = null;
}
const clearProgress = () => {
    reloadProgressName.value = '';
    setTimeout(() => {
        reloadProgress.value = 0;
    }, 10);
}

const onScrollBottom = () => {
    loadMore()
}

const updateHistory = () => {
    reloadProgressName.value = '更新历史库';
    ruleService.reloadHistory((p) => {
        // 取整
        p = Math.floor(p * 100)
        reloadProgress.value = p;
    }, () => {
        clearProgress();
        showDialog({
            title: '更新历史库成功',
            message: '更新历史库成功',
            noCancelBtn: true,
        });
    }, () => { clearProgress(); alert('更新历史库失败'); });
}
const updateProducts = () => {
    ruleService.reloadRules().then(() => {
        showDialog({
            title: '更新规则库成功',
            message: '更新规则库成功',
            noCancelBtn: true,
        });
    }).catch((e) => {
        alert('更新规则库失败! ' + e);
    });

}
const ry = window.cordova.plugins.RyBridge;
const checkResult = ref(null);
const scanedCode = ref('');
const barcodeListener = {
    success: (result) => {
        if (disableUse.value) {
            return;
        }

        sqlService.increaseUses().then(() => {
            sqlService.validateUses().then().catch(() => {
                disableUse.value = true;
                alert('已经超出体验限制! ');
            });
        })

        scanedCode.value = result.barcodeData
        if (!currentProduct.value) {
            alert('请先选择产品');
            return;
        }
        let cresult = null;
        ruleService.checkProduct(currentProduct.value, result.barcodeData, (r) => {
            cresult = r;
        })
        if (cresult.pass) {
            sqlService.existHistory(result.barcodeData).then((exist) => {
                if (!exist) {
                    checkResult.value = cresult;
                } else {
                    checkResult.value = {
                        pass: false,
                        passedContent: '',
                        errorContent: result.barcodeData,
                        leftContent: '',
                        errorMessage: '该产品已经存在于历史库中'
                    }
                }
            })
        } else {
            checkResult.value = cresult;
        }
        if (!cresult.pass) {
            window.navigator.vibrate(1000);
            showAlert.value = true;
            setTimeout(() => {
                showAlert.value = false;
            }, 1000);
        }

    },
    error: (error) => {
        console.log(error);
    }
}
ry.barcodeDeviceReady(() => {
    ry.addBarcodeEventListener(barcodeListener);
}, () => { });
onUnmounted(() => {
    console.log('remove barcode listener ' + barcodeListener.callbackId);
    ry.removeBarcodeEventListener(barcodeListener);
});
const currentPage = ref(0);
const pageSize = 10;

const loadMore = () => {
    currentPage.value++;
    ruleService.loadRules(currentPage.value, pageSize).then((data) => {
        if (!data || data.length == 0) {
            currentPage.value--;
            return;
        }
        products.value.push(...data);
    }).catch((e) => {
        alert('获取产品列表失败! ' + e);
    });
}

const loadAndShowProducts = () => {
    currentPage.value = 0;
    ruleService.loadRules(currentPage.value, pageSize).then((data) => {
        showProducts.value = true
        products.value = data;
    }).catch((e) => {
        alert('获取产品列表失败! ' + e);
    });
}
</script>
<style lang="scss" scoped>
.scanArea {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: 20px;
    color: #666;
}

.bottom-area {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
    left: 0;
    display: flex;
    justify-content: center;
}

.cell {
    border-bottom: 1px solid #ccc;
}

.title {
    color: var(--nut-button-info-background-color);
    margin: 10px;
}

.rule-item {
    margin: 10px;
    color: #666;
}

.tag-area {
    margin-top: 20px;
    height: 150px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80%;
    font-size: 20px;
}

.result-area {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #666;
    margin-top: 20px;
}
</style>